<template>
  <!-- 自动发布状态、自动发布更新 -->
  <div class="autopublish_container">
    <el-checkbox v-model="isContinuityNum" @change.native.stop="isCNChange" v-permission="['YJYY10001001002', 'YJYY10008002001']">
      {{mini?'连续':'全天连续号源'}}
      <el-tooltip class="item" effect="dark" content="全天连续号源：设置号源排班时，当天号源的号码将不区分班次全部为连续号码！（修改后会刷新当前模板，如有修改请先保存模板。）" placement="top-start">
        <i class="el-icon-question"></i>
      </el-tooltip>
    </el-checkbox>
    <el-divider direction="vertical"></el-divider>
    <span class="releaseauto" v-permission="['YJYY10001001002', 'YJYY10008002001']" @click="openAutoDialog" :title="checkroomModelObj.isAutoPublish?'自动发布':'未自动发布'">
      <i class="dot" :class="{isauto: checkroomModelObj.isAutoPublish}"></i>
      <template v-if="mini">
        {{checkroomModelObj.isAutoPublish?`自动${checkroomModelObj.publishWeeks?' '+checkroomModelObj.publishWeeks+'周':''}`:'未自动'}}
      </template>
      <template v-else>
        {{checkroomModelObj.isAutoPublish?`自动发布中${checkroomModelObj.publishWeeks?' '+checkroomModelObj.publishWeeks+'周':''}`:'未自动发布'}}
      </template>
    </span>

    <!-- 自动更新编辑弹框 -->
    <el-dialog
      title="机房号源模板自动发布"
      :visible.sync="autoDialog"
      :destroy-on-close="true"
      v-loading="loading"
      :close-on-click-modal="false"
      width="500px">
      <div>
        <el-form
          :model="appoFormData"
          class="ky-form-inline"
          label-width="100px"
        >
          <el-form-item label="自动发布" class="item-line-36" prop="auto">
            <div style="margin-top: 10px;">
              <el-switch
                v-model="appoFormData.auto"
                active-text="开启"
                inactive-text="关闭">
              </el-switch>
              <el-tooltip class="autotips" effect="dark" content="开启自动发布后，将自动根据号源模板进行自动发布，且按发布周期顺延" placement="top-start">
                <i class="el-icon-question" style="vertical-align: -2px;"></i>
              </el-tooltip>
            </div>
          </el-form-item>
          <el-form-item label="发布所有号源" class="item-line-36" prop="isAllPublish">
            <div style="margin-top: 10px;">
              <el-switch
                v-model="appoFormData.isAllPublish"
                active-text="开启"
                inactive-text="关闭">
              </el-switch>
              <el-tooltip class="autotips" effect="dark" content="开启发布所有号源后，将发布号源模板设置的所有号源，如果关闭，只发布设置的时令时间内的号源" placement="top-start">
                <i class="el-icon-question" style="vertical-align: -2px;"></i>
              </el-tooltip>
            </div>
          </el-form-item>
          <el-form-item label="发布周期">
            <el-select v-model="appoFormData.weeks" placeholder="请选择" style="width: 110px;">
              <el-option
                v-for="(item ,index) in cycleoptions"
                :key="index"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
            <el-input
              v-if="appoFormData.weeks === -1"
              v-model="appoFormData.weeksVal"
              placeholder="可输入1-24"
              maxlength="2"
              @keyup.native="setWeek"
              style="width: 160px;">
              <template slot="append">周</template>
            </el-input>
          </el-form-item>
        </el-form>
        <el-divider></el-divider>
        <div class="tips"><span class="label">发布提示：</span>开启自动发布后，会根据自动发布周来更新当前设置时令的排班时段号源，如：自动发布3周，则从当前日期的周开始合计3周，如果需要更新的周已存在号源，则这周不更新（举例：如果今天已经设置了号源，则本周不更新，更新后面2周）。</div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="autoDialog = false">取 消</el-button>
        <el-button type="primary" size="small" @click="autoPublishSend">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  putAppointmentlistdmbSetautopublish,
  putupdatecontinuitynum
} from '@/api/api'
import {
  getCheckroomModelAutoPublish
} from '@/api/room'
import { isNull, getRoomTagCurr, setRoomTagCurr, getRoomOptions } from '@/utils/utils'
export default {
  name: 'AutoPublishStatus',
  props: {
    mini: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      loading: false,
      checkroomModelObj: {
        id: 0, // 排班模板id
        isAutoPublish: 0, // 是否自动发布 0否，1是
        publishWeeks: 0, // 自动发布几周 0否，1是
        isIncludedHolidays: false, // 是否包含节假日
        isAllPublish: 0 // 是否发布所有号源 0否，1是
      },
      formdata: {
        room: []
      },

      // 自动发布编辑
      autoDialog: false,
      appoFormData: {
        weeks: 1,
        weeksVal: '',
        auto: false,
        isAllPublish: false
      },
      // 发布周期
      cycleoptions: [
        { label: '1周', value: 1 },
        { label: '2周', value: 2 },
        { label: '3周', value: 3 },
        { label: '4周', value: 4 },
        { label: '8周', value: 8 },
        { label: '其它', value: -1 }
      ],
      isContinuityNum: false // 提交的时候 0 不连续， 1连续

    }
  },
  methods: {
    // 获取链接参数
    getQueryString(name) {
      var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i')
      var r = window.location.search.substr(1).match(reg)
      console.warn('getQueryString=>r', r)
      if (r != null) return decodeURI(r[2])
      return null
    },
    init(room) {
      // console.log('autoPublishStatus=>init=>room', room)
      this.formdata.room = room && room.length > 0 ? room : this.formdata.room
      this.getCheckroomModelPost()
    },
    // 自动发布，机房对象数据获取
    async getCheckroomModelPost() {
      if (this.formdata.room.length === 0) return
      console.warn('this.formdata.room', this.formdata.room)
      const params = {
        HospitalCode: this.formdata.room[0],
        DepArea: this.formdata.room[1],
        Dep: this.formdata.room[2],
        ModalityType: this.formdata.room[3],
        CheckRoom: this.formdata.room[4]
      }
      const modality = this.getQueryString('modality')
      // // console.log('modality', modality)
      if (!isNull(modality) && !params.Modality) {
        params.Modality = modality
      } else {
        // 所选机房 $# [1]
        if (!isNull(getRoomTagCurr())) {
          params.Modality = getRoomTagCurr().split('$#')[1]
          params.CheckRoom = getRoomTagCurr().split('$#')[0]
        } else {
          if (!isNull(getRoomOptions())) {
            let currentRoom = getRoomOptions()[0].value
            // console.log('currentRoom', currentRoom)
            setRoomTagCurr(currentRoom)
            params.Modality = currentRoom.split('$#')[1]
            params.CheckRoom = currentRoom.split('$#')[0]
          }
        }
      }
      // console.log('params.CheckRoom', params.CheckRoom)
      // console.warn('getCheckroomModelPost=>params到了这里', params)
      const roomModel = await getCheckroomModelAutoPublish(params)
      // console.log('ModalityType', params)
      // console.log('roomModel', roomModel)
      this.tempAutoInit(roomModel)
    },
    tempAutoInit(tempObj) {
      this.checkroomModelObj = JSON.parse(JSON.stringify(tempObj))
      this.appoFormData.auto = !!tempObj.isAutoPublish
      this.appoFormData.isAllPublish = !!tempObj.isAllPublish
      this.appoFormData.weeks = tempObj.publishWeeks ? tempObj.publishWeeks : 1
      if (this.appoFormData.weeks) {
        const weekIndex = this.cycleoptions.findIndex(item => item.value === this.appoFormData.weeks)
        if (weekIndex === -1) {
          this.appoFormData.weeks = -1
          this.appoFormData.weeksVal = tempObj.publishWeeks
        }
      }
      this.isContinuityNum = !!tempObj.isContinuityNum
      this.$store.dispatch('user/setIsContinuityNum', tempObj.isContinuityNum)
    },
    // 输入周
    setWeek() {
      this.appoFormData.cycleVal = this.appoFormData.cycleVal ? this.appoFormData.cycleVal.replace(/\D/g, '') : ''
    },

    openAutoDialog() {
      this.autoDialog = true
    },
    // 自动发布更新提交
    autoPublishSend() {
      this.tempAutoEdit()
    },
    // 修改，机房自动排班
    tempAutoEdit() {
      const week = this.appoFormData.weeks > 0 ? this.appoFormData.weeks : this.appoFormData.weeksVal * 1
      const params = {
        hospitalCode: this.formdata.room[0],
        id: this.checkroomModelObj.id,
        isAutoPublish: this.appoFormData.auto ? 1 : 0,
        publishWeeks: week || 1,
        isIncludedHolidays: this.checkroomModelObj.isIncludedHolidays || 0,
        isAllPublish: this.appoFormData.isAllPublish ? 1 : 0
      }
      this.loading = true
      putAppointmentlistdmbSetautopublish(params).then(res => {
        this.loading = false
        if (res && res.code === 10000) {
          this.$message.success(res.message)
          this.checkroomModelObj.isAutoPublish = params.isAutoPublish
          this.checkroomModelObj.publishWeeks = params.publishWeeks
          this.checkroomModelObj.isAllPublish = params.isAllPublish
          this.autoDialog = false
          this.$emit('autoChange')
        }
      })
    },

    // 连续号源
    isCNChange() {
      // console.log(this.isContinuityNum)
      this.isContinuityNum = !this.isContinuityNum
      // this.$confirm('修改全天连续号源配置，将会修改时段号源号码，修改后的时段号源需要保存或发布后生效，是否继续?', '提示', {
      this.$confirm('设置号源排班时，当天号源的号码将不区分班次全部为连续号码！修改后会刷新当前模板，如有修改请先保存模板，是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        showClose: false
      }).then(() => {
        this.sendIsContinuityNum()
      }).catch(() => {
        // this.isContinuityNum = !this.isContinuityNum
      })
    },
    // 连续号源配置提交
    sendIsContinuityNum() {
      const params = {
        hospitalCode: this.formdata.room[0],
        id: this.checkroomModelObj.id,
        isContinuityNum: !this.isContinuityNum ? 1 : 0
      }
      putupdatecontinuitynum(params).then(res => {
        if (res && res.code === 10000) {
          this.isContinuityNum = !this.isContinuityNum
          this.$store.dispatch('user/setIsContinuityNum', this.isContinuityNum ? 1 : 0)
          this.$emit('autoChange')
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.autopublish_container{
  display: inline-block;
  margin:0 20px;
  text-align: left;
  /deep/ .el-dialog__body{
    padding: 4px 20px 20px;
  }
}
.releaseauto{
  cursor: pointer;
  font-size: 14px;
  .dot{
    display: inline-block;
    width: 8px;
    height: 8px;
    border-radius: 50%;
    margin-right: 8px;
    background-color: #EB5353;
  }
  .isauto{
    background-color: rgb(67, 207, 32);
  }
}
.tips{
  font-size: 12px;
  color: #666;
  line-height: 1.6em;
  .label{
    color: #333;
  }
}
</style>
